#include "audio_manager.h"
#include <QDebug>

AudioManager::AudioManager(QObject *parent) : QObject(parent)
{
    m_bgmPlayer = new QSoundEffect(this);
    m_bgmPlayer->setLoopCount(QSoundEffect::Infinite);
    m_isPlaying = false;
}

AudioManager::~AudioManager()
{
    if (m_bgmPlayer)
    {
        m_bgmPlayer->stop();
        delete m_bgmPlayer;
        m_bgmPlayer = nullptr;
    }
}
void AudioManager::setBgmPath(const QString &path)
{
    m_bgmPath = path;
    m_bgmPlayer->setSource(QUrl::fromLocalFile(path));
}

void AudioManager::toggleBgm()
{
    if (m_isPlaying)
    {
        m_bgmPlayer->stop();
    }
    else
    {
        if (m_bgmPath.isEmpty())
        {
            qWarning() << "BGM路径未设置";
            return;
        }
        if (m_bgmPlayer->status() == QSoundEffect::Error)
        {
            qWarning() << "BGM加载失败";
            return;
        }
        m_bgmPlayer->play();
    }
    m_isPlaying = !m_isPlaying;
}

void AudioManager::setVolume(int volume)
{
    volume = qBound(0, volume, 100);
    m_bgmPlayer->setVolume(volume / 100.0);
    emit volumeChanged(volume);
}

bool AudioManager::isPlaying() const
{
    return m_isPlaying;
}

void AudioManager::initBGM(const QString &path)
{
    setBgmPath(path);
}

